#include "Network.hpp"
WSAData Network::wsaData;
int Network::af;
int Network::protocol;
int Network::type;
Network::~Network()
{
    if(m_socket!=INVALID_SOCKET){
        closesocket(m_socket);
    }
}
int Network::init()
{
    return WSAStartup(MAKEWORD(2,2),&wsaData);
}

void Network::quit()
{
    WSACleanup();
}

void Network::setSocketInfo(int af, int type, int protocol)
{
    Network::af = af;
    Network::type = type;
    Network::protocol = protocol;
}

bool Network::createSocket()
{
    if(m_socket!=INVALID_SOCKET)    closesocket(m_socket);
    m_socket = socket(af,type,protocol);
    return m_socket!=INVALID_SOCKET;
}

bool Network::connect(const char *ip, int port)
{
    sockaddr_in con_sock;
    con_sock.sin_family=Network::af;
    con_sock.sin_addr.S_un.S_addr=inet_addr(ip);
    con_sock.sin_port=htons(port);
    return ::connect(m_socket,(sockaddr*)&con_sock,sizeof(con_sock))==0;
}

bool Network::bind(int port)
{
    sockaddr_in con_sock;
    con_sock.sin_family=Network::af;
    con_sock.sin_addr.S_un.S_addr=ADDR_ANY;
    con_sock.sin_port=htons(port);
    return ::bind(m_socket,(sockaddr*)&con_sock,sizeof(con_sock))==0;
}

bool Network::listen(int backlog)
{
    return ::listen(m_socket,backlog)==0;
}

bool Network::accept(NetworkMsg *networkMsg)
{
    networkMsg->addr_len=sizeof(networkMsg->sock_addr);
    SOCKET socket = ::accept(m_socket,(sockaddr*)&networkMsg->sock_addr,&networkMsg->addr_len);
    if(socket==INVALID_SOCKET){
        return false;
    }
    networkMsg->socket=socket;
    return true;
}

int Network::recv(SOCKET socket,char* buf, int buffSize, int flags)
{
    return ::recv(socket,buf,buffSize,flags);
}

int Network::send(SOCKET socket,const char* buf, int len, int flags)
{
    return ::send(socket,buf,len,flags);
}

SOCKET Network::getSocket()
{
    return m_socket;
}
